package com.aldobucchi.x.mx.rpc.http.HTTPService
{
	
	import com.adobe.net.URI;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.http.HTTPService;
	
	import com.aldobucchi.utils.Words;



	/**
	 * 
	 * This is a Tweaked HTTPService that knows how to tunnel ( a la restlet )
	 * method calls other than GET or POST
	 * 
	 * TODO: add link to relevant Restlet docs
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */
	public class TunnelingHTTPService extends HTTPService
	{
		
		public var methodParameterName:String = Words._method;
		
		private var weAreTunnelingFlag:Boolean = false;
		
		private var originalMethod:String = null;
		
		
		override public function get url():String
		{
			
			if ( weAreTunnelingFlag )
			{
				var uri:URI = new URI( super.url );
				uri.setQueryValue( methodParameterName , originalMethod.toUpperCase() );						
				return uri.toString();											
			}
			return super.url;
		}


		private function shouldTunnel():Boolean
		{
			if ( super.method == null ) 						return false;
			if ( super.method.toUpperCase() == Words._GET )	return false;
			if ( super.method.toUpperCase() == Words._POST )	return false;
			return true;
		}

		
		override public function send(parameters:Object=null):AsyncToken
		{
			
			if ( shouldTunnel() )		// tamper values
			{	
				weAreTunnelingFlag = true;
				originalMethod = method;
				method = Words._POST;
			}
			
			var token:AsyncToken = super.send( parameters );

			if ( weAreTunnelingFlag )	// restore
			{
				method = originalMethod;
				weAreTunnelingFlag = false;
			}
		
			return token;
		}
		
	}

}